package com.ruoyi.server.encode;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.server.enums.CmdConstants;
import com.ruoyi.server.pkg.SendMsg;
import com.ruoyi.server.read.BaseCenterReader;
import com.ruoyi.server.read.PrivateReader;
import com.ruoyi.server.thread.PullReceiptReader;
import com.ruoyi.server.utils.OnlineUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 入
 *
 * @author OpenACloud
 * @create 2024/6/3 21:54
 */
public class SendReceiveDecode extends MessageToMessageDecoder<TextWebSocketFrame> {


    private static final boolean AUTH_OPEN = false;
    private HashMap<Byte, BaseCenterReader> baseReaderMaps = new HashMap<>();

    public SendReceiveDecode(){

    }

    public SendReceiveDecode(HashMap<Byte, BaseCenterReader> baseReaderMaps){
        this.baseReaderMaps = baseReaderMaps;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame webSocketFrame, List<Object> objArrays) throws Exception {
        byte[] byAuth = webSocketFrame.content().array();
        if (byAuth.length > 6 && AUTH_OPEN) {
            int headAuth = byAuth[0];
            int tailAuth = byAuth[5];
            int nowAuth = headAuth + tailAuth;
            Long needAuth = ctx.attr(OnlineUtil.AUTH_BYTE).get();
            if(nowAuth != needAuth) {
                return;
            }
        }
        String sendContext = webSocketFrame.text();
        SendMsg sendMsg = JSONObject.parseObject(sendContext, SendMsg.class);
        Byte CMD = sendMsg.CMD;
        if(baseReaderMaps.containsKey(CMD)) {
            sendMsg.TIME = LocalDateTime.now();
            sendMsg.SENDID = ctx.channel().attr(OnlineUtil.SEND_ID).get();
            sendMsg.setReader(baseReaderMaps.get(CMD));
        }
        objArrays.add(sendMsg);
    }


}
